'use client';

import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Input,
  Select,
  Space,
  Tag,
  Avatar,
  Modal,
  Form,
  message,
  Popconfirm,
  Tooltip,
  Card,
  Row,
  Col,
  Statistic
} from 'antd';
import {
  UserOutlined,
  EditOutlined,
  DeleteOutlined,
  PlusOutlined,
  SearchOutlined,
  ReloadOutlined,
  UserAddOutlined,
  TeamOutlined,
  CrownOutlined,
  EyeOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import AdminLayout from '../AdminLayout';
import styles from './Users.module.scss';

const { Search } = Input;
const { Option } = Select;

interface User {
  id: string;
  username: string;
  email: string;
  role: 'super_admin' | 'admin' | 'editor' | 'user' | 'guest';
  display_name?: string;
  phone?: string;
  status: 'active' | 'inactive' | 'banned';
  email_verified: boolean;
  last_login?: string;
  login_count: number;
  created_at: string;
  updated_at: string;
}

interface UserListResponse {
  success: boolean;
  data: User[];
  total: number;
  page: number;
  limit: number;
  stats?: {
    total: number;
    active: number;
    inactive: number;
    banned: number;
    roles: Record<string, number>;
  };
}

interface CreateUserData {
  username: string;
  email: string;
  password: string;
  role: string;
  display_name?: string;
  phone?: string;
}

const UsersPage: React.FC = () => {
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [searchText, setSearchText] = useState('');
  const [roleFilter, setRoleFilter] = useState<string>('');
  const [statusFilter, setStatusFilter] = useState<string>('');
  const [stats, setStats] = useState<any>(null);
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [selectedUser, setSelectedUser] = useState<User | null>(null);
  const [createForm] = Form.useForm();
  const [editForm] = Form.useForm();

  // 获取用户列表
  const fetchUsers = async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams({
        page: currentPage.toString(),
        limit: pageSize.toString(),
        ...(searchText && { search: searchText }),
        ...(roleFilter && { role: roleFilter }),
        ...(statusFilter && { status: statusFilter })
      });

      const response = await fetch(`/api/admin/users?${params}`);
      const result: UserListResponse = await response.json();

      if (result.success) {
        setUsers(result.data);
        setTotal(result.total);
        setStats(result.stats);
      } else {
        message.error('获取用户列表失败');
      }
    } catch (error) {
      message.error('网络错误');
    } finally {
      setLoading(false);
    }
  };

  // 创建用户
  const handleCreateUser = async (values: CreateUserData) => {
    try {
      const response = await fetch('/api/admin/users', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(values),
      });

      const result = await response.json();
      if (result.success) {
        message.success('用户创建成功');
        setCreateModalVisible(false);
        createForm.resetFields();
        fetchUsers();
      } else {
        message.error(result.error || '创建用户失败');
      }
    } catch (error) {
      message.error('网络错误');
    }
  };

  // 更新用户
  const handleUpdateUser = async (values: Partial<User>) => {
    if (!selectedUser) return;

    try {
      const response = await fetch(`/api/admin/users/${selectedUser.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(values),
      });

      const result = await response.json();
      if (result.success) {
        message.success('用户更新成功');
        setEditModalVisible(false);
        editForm.resetFields();
        setSelectedUser(null);
        fetchUsers();
      } else {
        message.error(result.error || '更新用户失败');
      }
    } catch (error) {
      message.error('网络错误');
    }
  };

  // 删除用户
  const handleDeleteUser = async (userId: string) => {
    try {
      const response = await fetch(`/api/admin/users/${userId}`, {
        method: 'DELETE',
      });

      const result = await response.json();
      if (result.success) {
        message.success('用户删除成功');
        fetchUsers();
      } else {
        message.error(result.error || '删除用户失败');
      }
    } catch (error) {
      message.error('网络错误');
    }
  };

  // 角色标签颜色
  const getRoleColor = (role: string) => {
    const colors = {
      super_admin: 'red',
      admin: 'orange',
      editor: 'blue',
      user: 'green',
      guest: 'default'
    };
    return colors[role as keyof typeof colors] || 'default';
  };

  // 状态标签颜色
  const getStatusColor = (status: string) => {
    const colors = {
      active: 'success',
      inactive: 'warning',
      banned: 'error'
    };
    return colors[status as keyof typeof colors] || 'default';
  };

  // 角色中文名
  const getRoleName = (role: string) => {
    const names = {
      super_admin: '超级管理员',
      admin: '管理员',
      editor: '编辑者',
      user: '用户',
      guest: '访客'
    };
    return names[role as keyof typeof names] || role;
  };

  // 状态中文名
  const getStatusName = (status: string) => {
    const names = {
      active: '正常',
      inactive: '未激活',
      banned: '已封禁'
    };
    return names[status as keyof typeof names] || status;
  };

  // 表格列定义
  const columns: ColumnsType<User> = [
    {
      title: '用户',
      key: 'user',
      width: 200,
      render: (_, record) => (
        <Space>
          <Avatar 
            size="small" 
            icon={<UserOutlined />}
          />
          <div>
            <div className={styles.username}>{record.username}</div>
            <div className={styles.displayName}>{record.display_name || record.email}</div>
          </div>
        </Space>
      ),
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      width: 200,
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      width: 120,
      render: (role) => (
        <Tag color={getRoleColor(role)} icon={<CrownOutlined />}>
          {getRoleName(role)}
        </Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => (
        <Tag color={getStatusColor(status)}>
          {getStatusName(status)}
        </Tag>
      ),
    },
    {
      title: '登录次数',
      dataIndex: 'login_count',
      key: 'login_count',
      width: 100,
      sorter: true,
    },
    {
      title: '最后登录',
      dataIndex: 'last_login',
      key: 'last_login',
      width: 150,
      render: (date) => date ? new Date(date).toLocaleString() : '从未登录',
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 150,
      render: (date) => new Date(date).toLocaleString(),
      sorter: true,
    },
    {
      title: '操作',
      key: 'actions',
      width: 150,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button
              type="text"
              size="small"
              icon={<EyeOutlined />}
              onClick={() => {
                setSelectedUser(record);
                editForm.setFieldsValue(record);
                setEditModalVisible(true);
              }}
            />
          </Tooltip>
          <Tooltip title="编辑">
            <Button
              type="text"
              size="small"
              icon={<EditOutlined />}
              onClick={() => {
                setSelectedUser(record);
                editForm.setFieldsValue(record);
                setEditModalVisible(true);
              }}
            />
          </Tooltip>
          <Popconfirm
            title="确定要删除这个用户吗？"
            description="删除后将无法恢复，请谨慎操作。"
            onConfirm={() => handleDeleteUser(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Tooltip title="删除">
              <Button
                type="text"
                size="small"
                danger
                icon={<DeleteOutlined />}
              />
            </Tooltip>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  useEffect(() => {
    fetchUsers();
  }, [currentPage, pageSize, searchText, roleFilter, statusFilter]);

  return (
    <AdminLayout pageTitle="用户管理">
      <div className={styles.usersPage}>
        {/* 统计卡片 */}
        {stats && (
          <Row gutter={16} className={styles.statsRow}>
            <Col span={6}>
              <Card>
                <Statistic
                  title="总用户数"
                  value={stats.total}
                  prefix={<TeamOutlined />}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="正常用户"
                  value={stats.active}
                  valueStyle={{ color: '#3f8600' }}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="未激活用户"
                  value={stats.inactive}
                  valueStyle={{ color: '#cf1322' }}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="管理员数量"
                  value={(stats.roles?.admin || 0) + (stats.roles?.super_admin || 0)}
                  prefix={<CrownOutlined />}
                />
              </Card>
            </Col>
          </Row>
        )}

        {/* 搜索和筛选 */}
        <Card className={styles.filterCard}>
          <Row gutter={16} align="middle">
            <Col flex="auto">
              <Space size="middle">
                <Search
                  placeholder="搜索用户名、邮箱"
                  allowClear
                  style={{ width: 300 }}
                  onSearch={setSearchText}
                  enterButton={<SearchOutlined />}
                />
                <Select
                  placeholder="角色筛选"
                  allowClear
                  style={{ width: 120 }}
                  value={roleFilter}
                  onChange={setRoleFilter}
                >
                  <Option value="super_admin">超级管理员</Option>
                  <Option value="admin">管理员</Option>
                  <Option value="editor">编辑者</Option>
                  <Option value="user">用户</Option>
                  <Option value="guest">访客</Option>
                </Select>
                <Select
                  placeholder="状态筛选"
                  allowClear
                  style={{ width: 120 }}
                  value={statusFilter}
                  onChange={setStatusFilter}
                >
                  <Option value="active">正常</Option>
                  <Option value="inactive">未激活</Option>
                  <Option value="banned">已封禁</Option>
                </Select>
              </Space>
            </Col>
            <Col>
              <Space>
                <Button
                  icon={<ReloadOutlined />}
                  onClick={fetchUsers}
                  loading={loading}
                >
                  刷新
                </Button>
                <Button
                  type="primary"
                  icon={<UserAddOutlined />}
                  onClick={() => setCreateModalVisible(true)}
                >
                  新增用户
                </Button>
              </Space>
            </Col>
          </Row>
        </Card>

        {/* 用户表格 */}
        <Card>
          <Table<User>
            columns={columns}
            dataSource={users}
            rowKey="id"
            loading={loading}
            scroll={{ x: 1200 }}
            pagination={{
              current: currentPage,
              pageSize: pageSize,
              total: total,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
              onChange: (page, size) => {
                setCurrentPage(page);
                setPageSize(size || 20);
              },
            }}
          />
        </Card>

        {/* 创建用户弹窗 */}
        <Modal
          title={<><UserAddOutlined /> 新增用户</>}
          open={createModalVisible}
          onCancel={() => {
            setCreateModalVisible(false);
            createForm.resetFields();
          }}
          footer={null}
          width={600}
        >
          <Form
            form={createForm}
            layout="vertical"
            onFinish={handleCreateUser}
          >
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="username"
                  label="用户名"
                  rules={[
                    { required: true, message: '请输入用户名' },
                    { min: 3, message: '用户名至少3个字符' },
                    { max: 20, message: '用户名最多20个字符' }
                  ]}
                >
                  <Input placeholder="请输入用户名" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="email"
                  label="邮箱"
                  rules={[
                    { required: true, message: '请输入邮箱' },
                    { type: 'email', message: '请输入有效的邮箱地址' }
                  ]}
                >
                  <Input placeholder="请输入邮箱" />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="password"
                  label="密码"
                  rules={[
                    { required: true, message: '请输入密码' },
                    { min: 6, message: '密码至少6个字符' }
                  ]}
                >
                  <Input.Password placeholder="请输入密码" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="role"
                  label="角色"
                  rules={[{ required: true, message: '请选择角色' }]}
                >
                  <Select placeholder="请选择角色">
                    <Option value="user">用户</Option>
                    <Option value="editor">编辑者</Option>
                    <Option value="admin">管理员</Option>
                    <Option value="super_admin">超级管理员</Option>
                  </Select>
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="display_name"
                  label="显示名称"
                >
                  <Input placeholder="请输入显示名称" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="phone"
                  label="手机号"
                >
                  <Input placeholder="请输入手机号" />
                </Form.Item>
              </Col>
            </Row>
            <Form.Item>
              <Space style={{ width: '100%', justifyContent: 'flex-end' }}>
                <Button onClick={() => {
                  setCreateModalVisible(false);
                  createForm.resetFields();
                }}>
                  取消
                </Button>
                <Button type="primary" htmlType="submit">
                  创建
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>

        {/* 编辑用户弹窗 */}
        <Modal
          title={<><EditOutlined /> 编辑用户</>}
          open={editModalVisible}
          onCancel={() => {
            setEditModalVisible(false);
            editForm.resetFields();
            setSelectedUser(null);
          }}
          footer={null}
          width={600}
        >
          <Form
            form={editForm}
            layout="vertical"
            onFinish={handleUpdateUser}
          >
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="username"
                  label="用户名"
                  rules={[
                    { required: true, message: '请输入用户名' },
                    { min: 3, message: '用户名至少3个字符' },
                    { max: 20, message: '用户名最多20个字符' }
                  ]}
                >
                  <Input placeholder="请输入用户名" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="email"
                  label="邮箱"
                  rules={[
                    { required: true, message: '请输入邮箱' },
                    { type: 'email', message: '请输入有效的邮箱地址' }
                  ]}
                >
                  <Input placeholder="请输入邮箱" />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="role"
                  label="角色"
                  rules={[{ required: true, message: '请选择角色' }]}
                >
                  <Select placeholder="请选择角色">
                    <Option value="guest">访客</Option>
                    <Option value="user">用户</Option>
                    <Option value="editor">编辑者</Option>
                    <Option value="admin">管理员</Option>
                    <Option value="super_admin">超级管理员</Option>
                  </Select>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="status"
                  label="状态"
                  rules={[{ required: true, message: '请选择状态' }]}
                >
                  <Select placeholder="请选择状态">
                    <Option value="active">正常</Option>
                    <Option value="inactive">未激活</Option>
                    <Option value="banned">已封禁</Option>
                  </Select>
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="display_name"
                  label="显示名称"
                >
                  <Input placeholder="请输入显示名称" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="phone"
                  label="手机号"
                >
                  <Input placeholder="请输入手机号" />
                </Form.Item>
              </Col>
            </Row>
            <Form.Item
              name="password"
              label="新密码"
              help="留空则不修改密码"
            >
              <Input.Password placeholder="请输入新密码" />
            </Form.Item>
            <Form.Item>
              <Space style={{ width: '100%', justifyContent: 'flex-end' }}>
                <Button onClick={() => {
                  setEditModalVisible(false);
                  editForm.resetFields();
                  setSelectedUser(null);
                }}>
                  取消
                </Button>
                <Button type="primary" htmlType="submit">
                  保存
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </AdminLayout>
  );
};

export default UsersPage;